package middleware

import (
	adminService "news_for_deepseek_interface/service/admin"
	"strings"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")

		if !strings.HasPrefix(authHeader, "Bearer ") {
			c.AbortWithStatusJSON(401, Result{
				Success: false,
				Data:    "",
				Message: "Unauthorized",
			})
			return
		}

		//提取token
		token := strings.TrimPrefix(authHeader, "Bearer ")

		adminTokenStruct, err := adminService.FindToken(token)
		if err != nil {
			c.AbortWithStatusJSON(200, Result{
				Success: false,
				Data:    "",
				Message: "token失效",
			})
			return
		}

		c.Set("admin_id", adminTokenStruct.AdminId)

		c.Next()
	}
}
